// main layer
var g_mainLayer;
var MainLayer = cc.Layer.extend({
    ////////////////////////////
    _tileMap : null,
    ////////////////////////////
    _role : null,
    _hero : null,
    ////////////////////////////
    _enemyPosition : null,
    _enemies : null,
    ////////////////////////////
    _eBullets : null,
    _hBullets : null,
    ////////////////////////////
    _effectProxy : null,
    ////////////////////////////
    _isGameOver : false,
    //////////////////////////////
    _addedTanks : 0,
    ctor:function () {
        this._super();
        g_mainLayer=this;
        this._enemyPosition = new Array();
        this._enemies = new Array();
        this._hBullets = new Array();
        this._eBullets = new Array();
        ///////////////////////////////
        this.initTileMap();
        this.initEnemyPosition();
        return true;
    },
    onEnter:function () {
        this._super();
        this.addProxies();

        //this.addRole();
        this.addHero();
        this.addTouchEvent();

        this.scheduleOnce( this.delayToShowHero,1.0 );
        this.schedule( this.delayToAddEnemy,3.0 );

        this.scheduleUpdate();
        this.schedule( this.enemySwerve,10 );
    },
    onExit : function(){
        this._enemies.splice(0,this._enemies.length);
        this._enemyPosition.splice(0,this._enemyPosition.length);
        this._hBullets.splice(0,this._hBullets.length);
        this._eBullets.splice(0,this._eBullets.length);
        this._super();
    },
    /////////////////////////////////////////////////////////////////////
    initTileMap : function(){
        var filename = GetMapFile(g_gameLevel);
        var file = MainResource(filename);
        this._tileMap = new MapLayer(file);
        this.addChild(this._tileMap,MW.ORDER.MAP);
    },
    initEnemyPosition : function(){
        var dict,array = this._tileMap.getObjectsByName("enemy");
        for (var i = 0, len = array.length; i < len; i++) {
            dict = array[i];
            if (!dict)
                break;
            var x = dict["x"], y = dict["y"];//var width = dict["width"], height = dict["height"];
            var position = this._tileMap.pixelToPoint( cc.p( x,y ) );
            position = this._tileMap.pointToPixel( position);
            this._enemyPosition.push(position);
        }
    },
    ////////////////////////////////////////////////////////////////
    getEnemyPosition : function(){
        var index = GetRandom(0,this._enemyPosition.length-1);
        return this._enemyPosition[index];
    },
    ////////////////////////////////////////////////////////////////
    addRole : function(){
        var dict,array = this._tileMap.getObjectsByName("role");
        for (var i = 0, len = array.length; i < len; i++) {
            dict = array[i];
            if (!dict)
                break;
            var x = dict["x"], y = dict["y"];//var width = dict["width"], height = dict["height"];
            var filename = MainResource("role.png");
            this._role = new cc.Sprite( filename );
            var position = this._tileMap.pixelToPoint( cc.p( x,y ) );
            position = this._tileMap.pointToPixel( position);
            this._role.setPosition( position );
            this.addChild(this._role,MW.ORDER.TANK);
        }
    },
    addHero:function(){
        var dict,array = this._tileMap.getObjectsByName("hero");
        for (var i = 0, len = array.length; i < len; i++) {
            dict = array[i];
            if (!dict)
                break;
            var x = dict["x"], y = dict["y"],hp = dict["hHP"], spd = dict["hSpd"];
            var filename = MainResource("hero00.png");
            this._hero = new Hero( filename,parseInt(hp),parseInt(spd) );
            var position = this._tileMap.pixelToPoint( cc.p( x,y ) );
            position = this._tileMap.pointToPixel( position);
            this._hero.setPosition( position );
            this._hero.setVisible(false);
            this._hero.setLife(false);
            this.addChild(this._hero,MW.ORDER.TANK);
        }
    },
    addEnemy:function(){
        if(!this._isGameOver){
            var position = this.getEnemyPosition();
            if( position ){
                var filename = MainResource("ene00.png");
                var enemy = new Enemy( filename,20,150,66 );
                enemy.setPosition( position );

                this._effectProxy.playEnemyBornEffect(0,position);

                this.addChild(enemy,MW.ORDER.TANK);
                this._enemies.push( enemy );
                cc.log("*** add enemy at:  "+position);
            }
        }
    },
    ////////////////////////////////////////
    addTouchEvent : function(){
        cc.eventManager.addListener({
            event: cc.EventListener.TOUCH_ONE_BY_ONE,
            swallowTouches: true,
            onTouchBegan: this.onTouchBegan
        }, this );
    },
    addProxies : function(){
        this._effectProxy = new EffectProxy();
        this.addChild(this._effectProxy,MW.ORDER.EFFECT);
    },
    ////////////////////////////////////////////////////////////////
    addEBullets : function(bullet){
        this.addChild(bullet,MW.ORDER.BULLET);
        this._eBullets.push( bullet );
        cc.log("add a enemy bullet");
    },
    addHBullets : function(bullet){
        this.addChild(bullet,MW.ORDER.BULLET);
        this._hBullets.push( bullet );
        cc.log("add a hero bullet");
    },
    ////////////////////////////////////////////////////////////////
    onTouchBegan : function (touch, event) {
        var local = touch.getLocation();

        g_mainLayer.addEnemy();

        return true;
    },
    delayToShowHero : function(dt){
        var position = this._hero.getPosition();
        this._effectProxy.playHeroBornEffect(0,position);
        this._hero.setVisible(true);
        this._hero.setLife(true);
    },
    delayToAddEnemy : function(dt){
        var ui = GetUILayer();
        if( ui && this._addedTanks<ui.getTanks() ){
            ++this._addedTanks;
            this.addEnemy();
            this.schedule( this.delayToAddEnemy,GetRandom(5,10) );
        }else{
            this.unschedule( this.delayToAddEnemy );
        }
    },
    enemySwerve : function(dt){
        var enemies=this._enemies;
        for( var e=0;e<enemies.length;e++) {
            var enemy = enemies[e];
            if (null != enemy) {
                if(GetRandom(0,10)%2==0)continue;
                enemy.swerve(enemy.getDirectRand());
            }
        }
        this.schedule( this.enemySwerve,GetRandom(4,8) );
    },
    gameOver : function(){
        this._isGameOver = true;
        this.unscheduleAllCallbacks();
        var enemies=this._enemies;
        for( var e=0;e<enemies.length;e++) {
            var enemy = enemies[e];
            if (null != enemy) {
                enemy.unscheduleAllCallbacks();
            }
        }
        g_overLayer.setVisible(true);
        var filename = AudioResource("aFail.mp3");
        cc.audioEngine.playMusic(filename);
    },
    ////////////////////////////////////////////////////////////////
    update : function(dt){
        ////////////////hero///////////////////////
        var hero=this._hero;
        if( null!=hero&&hero.getLife() ){
            hero.moving(dt);
        }
        ////////////////enemy///////////////////////
        var enemies=this._enemies;
        for( var e=0;e<enemies.length;e++){
            var enemy = enemies[e];
            if( null!=enemy ){
                if( enemy.getLife() ){
                    enemy.moving(dt);
                }
            }else{
                this._enemies.splice(e,1);
                cc.log( "splice a null enemy from buffer" );
            }
        }
        ////////////////enemy bullet///////////////////////
        var eBullets=this._eBullets;
        for( var b=0;b<eBullets.length;b++){
            var bullet = eBullets[b];
            if( null!=bullet ){
                if( bullet.getLife() ){
                    bullet.moving(dt);

                    if( null!=hero&&hero.getLife()){
                        var hPos = hero.getPosition(),ePos = bullet.getPosition();
                        if(cc.rectIntersectsRect( hero.collideRect(hPos.x,hPos.y),bullet.collideRect(ePos.x,ePos.y) )  ){
                            bullet.recover();
                            hero.dead();
                            this.gameOver();
                        }
                    }
                    // thing collide checking
                    if( Collide(bullet) ){
                        bullet.recover();
                    }
                }
            }else{
                this._eBullets.splice(b,1);
                cc.log( "splice a null enemy bullet from buffer" );
            }
        }
        ////////////////hero bullet/////////////////////////
        var hBullets=this._hBullets;
        for( var b=0;b<hBullets.length;b++){
            var bullet = hBullets[b];
            if( null!=bullet ){
                if( bullet.getLife() ){
                    bullet.moving(dt);
                    // thing collide checking
                    if( Collide(bullet) ){
                        bullet.recover();
                    }
                    for( var e=0;e<enemies.length;e++){
                        var enemy = enemies[e];
                        if (null!=enemy&&enemy.getLife()) {
                            var ePos = enemy.getPosition(), hPos = bullet.getPosition();
                            if (cc.rectIntersectsRect(enemy.collideRect(ePos.x, ePos.y), bullet.collideRect(hPos.x, hPos.y))) {
                                bullet.recover();
                                enemy.dead();
                            }
                        }
                    }
                }
            }else{
                this._hBullets.splice(b,1);
                cc.log( "splice a null hero bullet from buffer" );
            }
        }
    }
});
///////////////////////////////////////////////
GetMainLayer=function(){
    if(g_mainLayer) {
        return g_mainLayer;
    }else{
        cc.log("g_mainLayer invalid");
        return null;
    }
}
//////////////////////////////////////////////
AddEBullet=function(bullet){
    var mainLayer=GetMainLayer();
    mainLayer.addEBullets(bullet);
}
AddHBullet=function(bullet){
    var mainLayer=GetMainLayer();
    mainLayer.addHBullets(bullet);
}
GetEBulletFromBuffer=function(){
    var mainLayer=GetMainLayer();
    var bullets=mainLayer._eBullets;
    for( var b=0;b<bullets.length;b++){
        var bullet = bullets[b];
        if( null!=bullet&&!bullet.getLife()  ){
            cc.log("get enemy bullet from buffer");
            return bullet;
        }
    }
    return null;
}
GetHBulletFromBuffer=function(){
    var mainLayer=GetMainLayer();
    var bullets=mainLayer._hBullets;
    for( var b=0;b<bullets.length;b++){
        var bullet = bullets[b];
        if( null!=bullet&&!bullet.getLife()  ){
            cc.log("get hero bullet from buffer");
            return bullet;
        }
    }
    return null;
}
//////////////////////////////////////////////

